package com.ytjj.qmyx.supplychain.api.ceb.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ytjj.qmyx.supplychain.api.ceb.config.CebParamConfig;
import com.ytjj.qmyx.supplychain.api.ceb.model.*;
import com.ytjj.qmyx.supplychain.api.ceb.model.response.CebDataUploadResp;
import com.ytjj.qmyx.supplychain.common.model.response.CebOrderGoodsResponse;
import com.ytjj.qmyx.supplychain.common.model.response.CebOrderResponse;
import com.ytjj.qmyx.supplychain.common.model.response.CebUploadReqResponse;
import com.ytjj.qmyx.supplychain.common.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Slf4j
public class CebUtil {
    /**
     * 联调企业返回实时数据接口地址
     */
    public static final String TEST_DATA_UPLOAD_URL="https://swapptest.singlewindow.cn/ceb2grab/grab/realTimeDataUpload";
    /**
     * 线上企业返回实时数据接口地址
     */
    public static final String DATA_UPLOAD_URL="https://customs.chinaport.gov.cn/ceb2grab/grab/realTimeDataUpload";
    /**
     * 组装签名字符串
     * @param cebUploadReqResponse
     * @return
     */
    public static String getCebSignData(CebUploadReqResponse cebUploadReqResponse, CebOrderResponse cebOrder, CebParamConfig cebParamConfig){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        PayExchangeInfoHeadVO payExchangeInfoHead = new PayExchangeInfoHeadVO();
        payExchangeInfoHead.setCurrency("142");
        payExchangeInfoHead.setEbpCode(cebParamConfig.getEbpCode());
        payExchangeInfoHead.setGuid(cebOrder.getGuid());
        payExchangeInfoHead.setInitalRequest(cebOrder.getInitalRequest());
        payExchangeInfoHead.setInitalResponse(cebOrder.getInitalResponse());
        payExchangeInfoHead.setNote(cebOrder.getNote());
        payExchangeInfoHead.setPayCode(cebOrder.getPayCode());
        payExchangeInfoHead.setPayTransactionId(cebOrder.getPayTransactionId());
        payExchangeInfoHead.setPayType(String.valueOf(cebOrder.getPayType()));
        payExchangeInfoHead.setTotalAmount(cebOrder.getTotalAmount().doubleValue());
        payExchangeInfoHead.setTradingTime(sdf.format(cebOrder.getTradingTime()));
        payExchangeInfoHead.setVerDept(cebOrder.getVerDept());
        List<PayExchangeInfoVO> payExchangeInfoList = new ArrayList<>();
        PayExchangeInfoVO payExchangeInfoVO = new PayExchangeInfoVO();
        List<GoodsInfoVO> goodsInfoVOList = new ArrayList<>();
        for(CebOrderGoodsResponse goodsResponse:cebOrder.getCebOrderGoodsList()){
            GoodsInfoVO goodsInfoVO = new GoodsInfoVO();
            goodsInfoVO.setGname(goodsResponse.getItemName());
            goodsInfoVO.setItemLink(goodsResponse.getItemLink());
            goodsInfoVOList.add(goodsInfoVO);
        }
        payExchangeInfoVO.setGoodsInfo(goodsInfoVOList);
        payExchangeInfoVO.setOrderNo(cebOrder.getOrderNo());
        payExchangeInfoVO.setRecpAccount(cebOrder.getRecpAccount());
        payExchangeInfoVO.setRecpCode(cebOrder.getRecpCode());
        payExchangeInfoVO.setRecpName(cebOrder.getRecpName());
        payExchangeInfoList.add(payExchangeInfoVO);

        StringBuilder cebSignDataBuilder = new StringBuilder();
        cebSignDataBuilder.append("\"sessionID\":\""+cebUploadReqResponse.getSessionId()+"\"");
        cebSignDataBuilder.append("||");
        cebSignDataBuilder.append("\"payExchangeInfoHead\":\""+ JSONObject.toJSONString(payExchangeInfoHead) +"\"");
        cebSignDataBuilder.append("||");
        cebSignDataBuilder.append("\"payExchangeInfoLists\":\""+JSONObject.toJSONString(payExchangeInfoList)+"\"");
        cebSignDataBuilder.append("||");
        cebSignDataBuilder.append("\"serviceTime\":\""+cebUploadReqResponse.getServiceTime()+"\"");
        log.info("getCebSignData={}",cebSignDataBuilder.toString());
        return cebSignDataBuilder.toString();
    }

    /**
     * 组装CEB311报文实体
     * @param cebOrderResponse
     * @param cebParamConfig
     * @return
     */
    public static CEB311MessageVO buildCEB311Message(CebOrderResponse cebOrderResponse,CebParamConfig cebParamConfig){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        CEB311MessageVO ceb311MessageVO = new CEB311MessageVO();
        CEB311OrderHeadVO orderHead=new CEB311OrderHeadVO();
        orderHead.setActuralPaid(cebOrderResponse.getTotalAmount());
        orderHead.setAppStatus("2");
        orderHead.setAppTime(sdf.format(new Date()));
        orderHead.setAppType("1");
        orderHead.setBatchNumbers(cebOrderResponse.getBatchNumbers());
        orderHead.setBuyerIdNumber(cebOrderResponse.getBuyerIdNumber());
        orderHead.setBuyerIdType(String.valueOf(cebOrderResponse.getBuyerIdType()));
        orderHead.setBuyerName(cebOrderResponse.getBuyerName());
        orderHead.setBuyerRegNo(cebOrderResponse.getBuyerRegNo());
        orderHead.setBuyerTelephone(cebOrderResponse.getBuyerTelephone());
        orderHead.setConsignee(cebOrderResponse.getConsignee());
        orderHead.setConsigneeAddress(cebOrderResponse.getConsigneeAddress());
        orderHead.setConsigneeDistrict(cebOrderResponse.getConsigneeDistrict());
        orderHead.setConsigneeTelephone(cebOrderResponse.getConsigneeTelephone());
        orderHead.setCurrency("142");
        orderHead.setDiscount(BigDecimal.ZERO);
        orderHead.setEbcCode(cebParamConfig.getEbcCode());
        orderHead.setEbcName(cebParamConfig.getEbcName());
        orderHead.setEbpCode(cebParamConfig.getEbpCode());
        orderHead.setEbpName(cebParamConfig.getEbpName());
        orderHead.setFreight(BigDecimal.ZERO);
        orderHead.setGoodsValue(cebOrderResponse.getTotalAmount());
        orderHead.setGuid(cebOrderResponse.getGuid());
        orderHead.setNote(cebOrderResponse.getNote());
        orderHead.setOrderNo(cebOrderResponse.getOrderNo());
        orderHead.setOrderType("I");
        orderHead.setPayCode(cebOrderResponse.getPayCode());
        orderHead.setPayName(cebOrderResponse.getPayName());
        orderHead.setPayTransactionId(cebOrderResponse.getPayTransactionId());
        orderHead.setTaxTotal(BigDecimal.ZERO);
        List<CEB311OrderInfoVO> orderList=new ArrayList<>();
        int gnum=1;
        for(CebOrderGoodsResponse goodsResponse:cebOrderResponse.getCebOrderGoodsList()){
            CEB311OrderInfoVO ceb311OrderInfoVO=new CEB311OrderInfoVO();
            ceb311OrderInfoVO.setBarCode(goodsResponse.getBarCode());
            ceb311OrderInfoVO.setCountry(goodsResponse.getCountry());
            ceb311OrderInfoVO.setCurrency(goodsResponse.getCurrency());
            ceb311OrderInfoVO.setGmodel(goodsResponse.getGmodel());
            ceb311OrderInfoVO.setGnum(gnum);
            ceb311OrderInfoVO.setItemDescribe(goodsResponse.getItemDescribe());
            ceb311OrderInfoVO.setItemName(goodsResponse.getItemName());
            ceb311OrderInfoVO.setItemNo(goodsResponse.getItemNo());
            ceb311OrderInfoVO.setNote(goodsResponse.getNote());
            ceb311OrderInfoVO.setPrice(goodsResponse.getPrice());
            ceb311OrderInfoVO.setQty(new BigDecimal(goodsResponse.getQty()));
            ceb311OrderInfoVO.setTotalPrice(goodsResponse.getTotalPrice());
            ceb311OrderInfoVO.setUnit(goodsResponse.getUnit());
            orderList.add(ceb311OrderInfoVO);
            gnum++;
        }
        CEB311BaseTransferVO baseTransfer=new CEB311BaseTransferVO();
        baseTransfer.setCopCode(cebParamConfig.getCopCode());
        baseTransfer.setCopName(cebParamConfig.getCopName());
        baseTransfer.setDxpId(cebParamConfig.getDxpId());
        baseTransfer.setDxpMode(cebParamConfig.getDxpMode());
        baseTransfer.setNote("");
        ceb311MessageVO.setOrderHead(orderHead);
        ceb311MessageVO.setOrderList(orderList);
        ceb311MessageVO.setBaseTransfer(baseTransfer);
        return ceb311MessageVO;
    }

    /**
     * 上报实时数据
     * @param payExInfoVO
     * @param isTest 是否联调环境
     * @return
     */
    public static CebDataUploadResp realTimeDataUpload(PayExInfoVO payExInfoVO,boolean isTest) {
        String payExInfoStr=JSONObject.toJSONString(payExInfoVO);
        HashMap<String,String> paramMap=new HashMap<>();
        paramMap.put("payExInfoStr", payExInfoStr);
        log.info("realTimeDataUpload===========payExInfoStr={}",payExInfoStr);
        String requestUrl=DATA_UPLOAD_URL;
        if(isTest){
            requestUrl=TEST_DATA_UPLOAD_URL;
        }
        //注意请求post方式（x-www-form-urlencoded）编码必须为UTF-8
        String returnStr=HttpClientUtil.doPost(requestUrl,paramMap,"UTF-8");
        log.info("realTimeDataUpload===========returnStr={}",returnStr);
        if(StringUtils.isNotBlank(returnStr)){
            return JSON.parseObject(returnStr,CebDataUploadResp.class);
        }
        return null;
    }
}
